package com.hzyl.famousreader.view.activity;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import cn.pedant.SweetAlert.SweetAlertDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.*;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.umeng.analytics.MobclickAgent;
import com.hzyl.famousreader.Constant;
import com.hzyl.famousreader.R;
import com.hzyl.famousreader.repository.webservice.RetrofitClient;
import com.hzyl.famousreader.repository.webservice.api.UserService;
import com.hzyl.famousreader.repository.webservice.model.Token;
import com.hzyl.famousreader.router.Router;
import com.hzyl.famousreader.databinding.*;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.hzyl.famousreader.App.WECHAT_API;

/**
 * 登陆页
 */
@Route(path = "/login/login", name = "用户登陆页")
public class LoginActivity extends AppCompatActivity {

  private ActivityLoginBinding binding;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    binding = DataBindingUtil.setContentView(this, R.layout.activity_login);

    BarUtils.setStatusBarColor(this, getResources().getColor(R.color.bg_sky_blue), 0);

    binding.forgetPassword.setOnClickListener(v -> ARouter.getInstance().build(Router.ACTIVITY_RETRIEVE_PASSWORD).navigation());

    binding.toRegister.setOnClickListener(v -> ARouter.getInstance().build(Router.ACTIVITY_REGISTER).navigation());

    binding.loginBtnLogin.setOnClickListener(v -> {
      String username = binding.username.getText().toString();
      String password = binding.pwd.getText().toString();
      if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
        ToastUtils.showShort("请输入账号密码");
        return;
      }
      UserService userService = RetrofitClient.getInstance().create(UserService.class);
      userService.login(Constant.Authorization, "password", username, password).enqueue(new Callback<Token>() {
        @Override
        public void onResponse(Call<Token> call, Response<Token> response) {
          Token token = response.body();
          if (token != null) {
            SPUtils.getInstance().put(Constant.SP_IS_LOGIN, true);
            SPUtils.getInstance().put(Constant.SP_ACCESS_TOKEN, token.getAccessToken());
            SPUtils.getInstance().put(Constant.SP_REFRESH_TOKEN, token.getRefreshToken());
            SPUtils.getInstance().put(Constant.SP_USER_NAME, username);
            ToastUtils.showShort("成功登陆");
            ActivityUtils.startActivity(MainActivity.class);
          } else {
            ToastUtils.showShort("登陆失败!");
          }
        }

        @Override
        public void onFailure(Call<Token> call, Throwable t) {
          ToastUtils.showShort("登陆失败!");
        }
      });
    });

    binding.loginIvWechat.setOnClickListener(v -> {
      if(WECHAT_API.isWXAppInstalled()) {
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "diandi_wx_login";
        boolean isSuccess = WECHAT_API.sendReq(req);
      } else {
        new SweetAlertDialog(ActivityUtils.getTopActivity(), SweetAlertDialog.WARNING_TYPE)
          .setTitleText("请先安装微信，再使用微信登陆")
          .show();
        return;
      }
    });
  }

  @Override
  protected void onPause() {
    super.onPause();
    MobclickAgent.onPageEnd("登陆页");
    MobclickAgent.onPause(this);
  }

  @Override
  protected void onResume() {
    super.onResume();
    MobclickAgent.onPageStart("登陆页");
    MobclickAgent.onResume(this);
  }
}
